package com.jfast.framework.orm.dataSource;

import com.jfast.framework.log.Logger;
import com.jfast.framework.orm.config.DataSourceConfig;
import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

public class C3p0DataSourceFactory extends AbstractDataSource {

	private static final Logger logger = Logger.getLogger(C3p0DataSourceFactory.class);
	private ComboPooledDataSource dataSource;
	
	public C3p0DataSourceFactory(DataSourceConfig dataSourceConfig) {
		super(dataSourceConfig);
	}

	@Override
	public DataSource getDataSource() {
		return dataSource;
	}

	@Override
	public void initDataSource(DataSourceConfig dataSourceConfig) {
		dataSource = new ComboPooledDataSource();
		try {
			dataSource.setJdbcUrl(dataSourceConfig.getUrl());
			dataSource.setUser(dataSourceConfig.getUsername());
			dataSource.setPassword(dataSourceConfig.getPassword());
			dataSource.setMaxPoolSize(dataSourceConfig.getMaxActive());
			dataSource.setMinPoolSize(dataSourceConfig.getMinIdle());
			dataSource.setInitialPoolSize(dataSourceConfig.getInitialSize());
			dataSource.setDriverClass(dataSourceConfig.getDriverClassName());
		} catch (PropertyVetoException e) {
			dataSource = null; 
			logger.error("C3p0DataSource lodding error",e); 
		}
	}
}
